// const APP = getApp()
const tools = require('../../utils/tools')
import cache from "../../utils/cache.js";
import api from "../../api/index.js";
Page({
  data: {
    page: 1,
    peisongType: 'zq', // zq 自取，kd 配送
    showCartPop: false, // 是否显示购物车列表
    showGoodsDetailPOP: false, // 是否显示商品详情
    shopIsOpened: false, // 是否营业
    location: {},
    companyList: [],
    currentCompany: {},
    goods: [],
    menuButtonBoundingClientRect: wx.getMenuButtonBoundingClientRect(),
    showFirstPics(pics) {
      if (pics) {
        return pics.split(",")[0];
      } else {
        return pics;
      }
    }
  },
  onLoad: function (e) {
    getApp().initLanguage(this)
    //加载商品分类
    api.categoryList({
      method: "POST",
      data: {},
    }).then((res) => {
      this.setData({
        location,
        categories: res.data,
        activeKey: 0 //默认选择
      })
      return res.data[0];
    }).then((res) => {
      //加载商品
      this.getGoodsList(res)
    })
    //当前门店
    let _this = this
    cache.getCompanyList()
    .then((res) => {
      let currentCompany = res[0]
      _this.setData({
        companyList: res,
        currentCompany,
      })
      wx.setStorageSync('currentCompany', currentCompany)
    })
    
  },
  onShow: function () {
    //从本地缓存中获取配送方式
    const peisongType = wx.getStorageSync('peisongType')
    const currentCompany = wx.getStorageSync('currentCompany')
    if (peisongType) {
      this.setData({
        peisongType
      })
    }
    if (currentCompany) {
      this.setData({
        currentCompany
      })
    }
    this.shippingCarInfo()
    //自动打开购物车
    if (getApp().globalData.tabBar.shopCarStatus) {
      getApp().globalData.tabBar.shopCarStatus = false
      this.setData({
        showCartPop: true
      })
    }
  },
  changePeisongType(e) {
    const peisongType = e.currentTarget.dataset.type
    this.setData({
      peisongType
    })
    wx.setStorageSync('peisongType', peisongType)
  },
  async getGoodsList(goodsType) {
    api.goodsListPage({
      method: "POST",
      data: {
        goodsTypeId: goodsType.id
      },
    }).then((res) => {
      this.setData({
        goods: res.data.records,
      })
    })
  },
  _onReachBottom() {
    this.data.page++
  },
  categoryClick(e) {
    const index = e.currentTarget.dataset.idx
    const categorySelected = this.data.categories[index]
    this.setData({
      categorySelected
    })
    this.getGoodsList(categorySelected)
  },
  async shippingCarInfo() {
    api.shoppingCartBill({
      method: "POST",
      data: {},
    }).then((res) => {
      this.setData({
        shippingCar: res.data
      })
    })
    this.processBadge()
  },
  showCartPop() {
    this.setData({
      showCartPop: !this.data.showCartPop
    })
  },
  hideCartPop() {
    this.setData({
      showCartPop: false
    })
  },

  async skuClick(e) {
    const index1 = e.currentTarget.dataset.idx1
    const index2 = e.currentTarget.dataset.idx2
    const curGoodsMap = this.data.curGoodsMap
    curGoodsMap.goodsAttrPOS[index1].goodsAttrValues.forEach(ele => {
      ele.selected = false
    })
    curGoodsMap.goodsAttrPOS[index1].goodsAttrValues[index2].selected = true
    /**
     * 判断以前的购物车中是否已包含相同规格的商品
     */
    let num = this.haveSameSkuGoodsInCarAndReturnNum(curGoodsMap, this.data.shippingCar.listShoppingCart)
    curGoodsMap.number = num
    this.setData({
      curGoodsMap
    })
  },
  /**
   * 返回数量
   * @param {*} curGoodsMap 当前选中商品
   * @param {*} listShoppingCart 历史购物车
   */
  haveSameSkuGoodsInCarAndReturnNum(curGoodsMap, listShoppingCart) {
    //当前商品选中的sku
    let curGoodsSkuSelect = {}
    for (let item of curGoodsMap.goodsAttrPOS) {
      for (let item2 of item.goodsAttrValues) {
        if (item2.selected) {
          curGoodsSkuSelect[item.id] = item2.id
          break
        }
      }
    }
    let commonGoodsList = listShoppingCart.filter(i => i.goodsId == curGoodsMap.id);
    for (let item of commonGoodsList) {
      if (JSON.stringify(item.skuItem) === JSON.stringify(curGoodsSkuSelect)) {
        return item.num; //返回购物车中已存在的数量
      }
    }
    return 1; //返回数量1
  },
  /**
   * 没有sku属性的商品
   * @param {*} e 
   */
  async addCartNoSku(e) {
    const index = e.currentTarget.dataset.idx
    const goodsPO = this.data.goods[index]
    //没有规则只过滤商品id即可
    let cartGoods = this.data.shippingCar?.listShoppingCart?.find(i => i.goodsId === goodsPO.id);
    api.addShoppingCart({
      method: "POST",
      data: {
        id: cartGoods ? cartGoods.id : null,
        goodsId: goodsPO.id,
        goodsName: goodsPO.goodsName,
        num: cartGoods ? cartGoods.num + 1 : 1,
      },
    }).then((res) => {
      this.shippingCarInfo()
    })
  },
  async addCartWithSku() {
    const curGoodsMap = this.data.curGoodsMap
    const selectInfo = this.getSelectAttr(curGoodsMap)
    if (!selectInfo.canSubmit) {
      wx.showToast({
        title: '请完善选择',
        icon: 'error',
        duration: 2000
      })
    } else {
      let paramData = {
        goodsId: curGoodsMap.id,
        goodsName: curGoodsMap.goodsName,
        num: curGoodsMap.number,
        skuItem: selectInfo.selectKey,
        skuName: tools.objToString(selectInfo.selectKeyName)
      }
      let cartGoods = this.data.shippingCar?.listShoppingCart?.filter(i => i.goodsId === curGoodsMap.id).find(i => i.skuName === paramData.skuName);
      paramData.id = cartGoods ? cartGoods.id : null
      api.addShoppingCart({
        method: "POST",
        data: paramData,
      }).then((res) => {
        this.hideGoodsDetailPOP()
        this.shippingCarInfo()
      })
    }
  },
  async cartStepChange(e) {
    const index = e.currentTarget.dataset.idx
    const item = this.data.shippingCar.listShoppingCart[index]
    item.num = e.detail
    api.updateshoppingCartNum({
      method: "POST",
      data: item,
    }).then((res) => {
      this.shippingCarInfo()
      this.processBadge()
    })
  },
  goodsStepChange(e) {
    const curGoodsMap = this.data.curGoodsMap
    curGoodsMap.number = e.detail
    this.setData({
      curGoodsMap
    })
  },
  getSelectAttr(curGoodsMap) {
    let selectKey = {}
    let selectKeyName = {}
    if (!curGoodsMap.goodsAttrPOS) {
      canAddCar = true;
      return {};
    }
    let selectAttrValuesNum = 0
    for (let item of curGoodsMap.goodsAttrPOS) {
      if (!item.goodsAttrValues) {
        continue
      }
      let selectAttrValue = null;
      for (let itemAttrValue of item.goodsAttrValues) {
        if (itemAttrValue.selected) {
          selectAttrValue = itemAttrValue;
          selectAttrValuesNum++
          break
        }
      }
      if (selectAttrValue) {
        selectKey[item.id] = selectAttrValue.id
        selectKeyName[item.attrName] = selectAttrValue.attrValueName
      }
    }
    let canSubmit = false
    if (selectAttrValuesNum == curGoodsMap.goodsAttrPOS.length) {
      canSubmit = true
    }
    return {
      selectKey,
      selectKeyName,
      canSubmit
    }
  },
  async clearCart() {
    let listShoppingCart = this.data.shippingCar.listShoppingCart;
    api.cleanShoppingCart({
      method: "POST",
      data: {
        shoppingCartIds: listShoppingCart.map(item => item.id)
      },
    }).then((res) => {
      this.shippingCarInfo()
    }).then((res) => {
      this.setData({
        showCartPop: false
      })
    })
  },
  async showGoodsDetailPOP(e) {
    const index = e.currentTarget.dataset.idx
    this._showGoodsDetailPOP(this.data.goods[index])
  },
  async _showGoodsDetailPOP(curGoodsMap) {
    for (let item of curGoodsMap.goodsAttrPOS) {
      if (!item.goodsAttrValues) {
        continue
      }
      //先设置全部选中==>后设置第一个选中
      for (let item2 of item.goodsAttrValues) {
        item2.selected = false
      }
      item.goodsAttrValues[0].selected = true
    }
    curGoodsMap.number = this.haveSameSkuGoodsInCarAndReturnNum(curGoodsMap, this.data.shippingCar.listShoppingCart)
    this.setData({
      showGoodsDetailPOP: true, //打开规格弹框
      curGoodsMap
    })
  },
  hideGoodsDetailPOP() {
    this.setData({
      showGoodsDetailPOP: false
    })
  },
  goPay() {
    wx.navigateTo({
      url: '/pages/pay/index',
    })
  },
  processBadge() {
    // Badge processing logic can be implemented here if needed
  },
  selectshop() {
    wx.navigateTo({
      url: '/pages/company/index?modelType=2',
    })
  },
  goGoodsDetail(e) {
    const index = e.currentTarget.dataset.idx
    const goodsId = this.data.goods[index].id
    wx.navigateTo({
      url: '/pages/goods-details/index?id=' + goodsId,
    })
  },
  changeLang() {
    getApp().changeLang(this)
  },
  //--------------------------------------widgetOrder-----------------------------------------------
  widgetOrderCanceCard(){
    this.setData({
      showGoodsDetailPOP: false
    })
  }
})